import logging
import time
from threading import Thread, Event
from PIL import Image
from io import BytesIO
from dataStore import GlobalVar
from SubFunction import *
from inference import GenModule
from util import get_camera_list
from multiprocessing import Queue

logger = logging.getLogger("yolov5")
logger.setLevel(level=logging.INFO)
handler = logging.FileHandler("log.txt")
handler.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)

console = logging.StreamHandler()
console.setLevel(logging.INFO)

logger.addHandler(handler)
logger.addHandler(console)

import configparser
import os
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
cf = configparser.ConfigParser()
cf.read(os.path.join(BASE_DIR,"config.ini"), encoding='UTF-8')
front_weight=cf.get("weight","front_weight")
back_weight=cf.get("weight","back_weight")
weights_dict = {
    '1': [os.path.join(BASE_DIR,front_weight)],
    '2': [os.path.join(BASE_DIR,back_weight)],
}
# alarm type请在config.ini中查找自己的数字
func_dict = {
    '1': GenModule,  # 学生
    '2': GenModule,  # 教师
}
program = {}
started_evt = Event()

def save_image_from_bytes(byte_stream, output_path):
    # 将字节流转换为图像
    image = Image.open(BytesIO(byte_stream))
    # 保存图像到指定路径
    image.save(output_path)


# def start(port,list_,gpu_id):
def start(list_):
    global is_class
    global interval_frame
    src_list = []
    camera_list = []
    person_type = 1
    datas = get_camera_list(int(list_.port))  # 正式运行时打开这个，从后端获取视频流数

    for index,data in enumerate(datas):
        src_list.append(data['path'])
        camera_list.append(data['camera_id'])
        # dict_ = {data['camera_id']:Queue()}
        # list_.append(dict_)
        person_type = data["person_type"]
    sub_weight = weights_dict[str(person_type)]  # 权重
    print(sub_weight)
    sub_addr = src_list
    params = {"camera_id": 0, "created_at": "", "data_id": "", 'data': "", "person_type": '1',
              "event_level": "", "event_type": "", "screenshot_url": "", "video_url": ""}
    personTrack = False
    if person_type == 1:
        imagesize = 640
    else:
        imagesize = 640
        personTrack=True
    sub_func = GenModule(src_list=sub_addr,  # 视频源
                    weight=sub_weight,  # 权重
                    params=params,
                    fps_show=False,  # fps显示 # 丢帧模拟
                    track=personTrack,  # 跟踪
                    msg_send=True,  # 警报发送
                    imagesize=imagesize,
                    half=True,
                    camera_list=camera_list,  # 摄像头数组
                    Time_time=0,  # 隔多少帧检测一次
                    device=str(list_.gpu_id),
                    COUNTS=5,  # 间隔30帧
                    FramesListening=1,  # 听讲人数，间隔1min
                    FramesPeople=1,  # 教室人数，间隔1min
                    port=list_.port,
                    person_type=person_type
                    )
    common_fun(list_,hoisting=sub_func)

def common_fun(list_,hoisting):
    print("开始执行")
    workThred(list_,hoisting, started_evt)

def workThred(list_,hoisting, started_evt):
    print('countdown starting')
    global send_data
    global is_class
    global camera_map
    global fight_list
    global fight_num
    global frameNum
    frameNum = 1
    while True:
        hoisting.execute_func(list_) #
        # print("126-->",list_[0]["25"].qsize())
        # print(hoisting.stopTime)
        # time.sleep(hoisting.stopTime * 2)

if __name__ == '__main__':
    # 一个字典，ke
    dict_ = {}
    port = '5001'
    dict_['5001'] = [{"25":Queue()},{"27":Queue},{"28":Queue}]
    start(port,dict_[port])



